package org.example.loadBalancers;


import lombok.Getter;
import lombok.Setter;
import org.example.ServiceContext;
import org.example.ServiceInstance;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.PostConstruct;
import java.util.LinkedHashSet;

//负载均衡器抽象基类
@Getter
@Setter
public abstract class LoadBalancer {


    //给子类 注入核心服务上下文用
    //核心服务上下文
    protected ServiceContext serviceContext;

    //名字用于区分负载均衡策略
    protected String name;


    //抽象方法 不同策略获得服务实例
    public abstract ServiceInstance getServiceInstance(String serviceName);






    //子类重复的搬过来


    //方便给子类调用的构造器
    public LoadBalancer(String name){
        this.name = name;
    }

    //根据名称获取服务实例列表 方便给子类复用而不暴露serviceContext
    public LinkedHashSet<ServiceInstance> getServiceInstances(String serviceName) {
        return (LinkedHashSet<ServiceInstance>) serviceContext.getServices(serviceName);
    }

    //根据服务名称获取服务数量
    public int getServiceCount(String serviceName) {
        return serviceContext.getServices(serviceName).size();
    }

    // setServiceContext 方法可以由子类使用 @Autowired 自动注入
    @Autowired
    public void setServiceContext(ServiceContext serviceContext) {
        this.serviceContext = serviceContext;
    }


    @PostConstruct
    public void init() {
        System.out.println("初始化负载均衡器完成" +getName());
    }

}
